package com.party.web.biz.sign;

import com.google.common.base.Function;
import com.party.common.paging.Page;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.sign.SignApply;
import com.party.core.model.sign.SignProject;
import com.party.core.model.sign.SignProjectAuthor;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.sign.ISignApplyService;
import com.party.core.service.sign.ISignGroupService;
import com.party.core.service.sign.ISignProjectService;
import com.party.core.service.sign.ISignRecordService;
import com.party.web.biz.file.FileBizService;
import com.party.web.utils.RealmUtils;
import com.party.web.web.dto.output.sign.SignProjectOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;
import java.util.Map;

/**
 * 签到项目业务接口
 * Created by wei.li
 *
 * @date 2017/6/7 0007
 * @time 9:38
 */

@Service
public class SignProjectBizService {

    @Autowired
    private FileBizService fileBizService;

    @Autowired
    private ISignProjectService signProjectService;

    @Autowired
    private CosBizService cosBizService;

    @Autowired
    private ISignGroupService signGroupService;

    @Autowired
    private ISignApplyService signApplyService;

    @Autowired
    private ISignRecordService signRecordService;

    @Autowired
    private IMemberGroupService memberGroupService;

    Logger logger = LoggerFactory.getLogger(getClass());

    private static final String CODE_PATH = "/signProject/";

    private static final String url = "sign/sign_pro.html?id=";

    /**
     * 签到项目输出视图
     *
     * @param signProjectAuthor 签到项目
     * @param page              分页参数
     * @return 签到项目
     */
    public List<SignProjectOutput> list(SignProjectAuthor signProjectAuthor, Page page, Map<String, Object> params) {
        MemberGroup member = RealmUtils.getCurrentUser();
        List<String> orgIds = memberGroupService.getChildWithMy(member.getId());
        params.put("orgIds", orgIds);
        List<SignProjectAuthor> list = signProjectService.projectAuthorList(signProjectAuthor, params, page);
        List<SignProjectOutput> outputList = LangUtils.transform(list, new Function<SignProjectAuthor, SignProjectOutput>() {
            @Override
            public SignProjectOutput apply(SignProjectAuthor signProjectAuthor) {
                String filePath = fileBizService.getUploadCIPath(signProjectAuthor.getCreateBy(), "signProject");
                SignProjectOutput signProjectOutput = SignProjectOutput.transform(signProjectAuthor);
                String url = cosBizService.getPreviewPictureUrl(filePath + signProjectAuthor.getId());
                signProjectOutput.setQrCode(url);
                return signProjectOutput;
            }
        });

        return outputList;
    }

    /**
     * 删除项目业务
     *
     * @param projectId 项目编号
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean deleteProjectBiz(String projectId) {
        boolean endResult = true;
        String memberId = null;
        try {
            if (StringUtils.isEmpty(projectId)) {
                endResult = false;
                return endResult;
            }
            SignProject signProject = signProjectService.get(projectId);
            if (signProject == null) {
                endResult = false;
                return endResult;
            }
            memberId = signProject.getCreateBy();
            signGroupService.deleteByProjectId(projectId);
            List<SignApply> signApplies = signApplyService.findByProject(projectId);
            for (SignApply signApply : signApplies) {
                signRecordService.deleteByApplyId(signApply.getId());
                signApplyService.delete(signApply.getId());
            }
            signProjectService.delete(projectId);
        } catch (Exception e) {
            endResult = false;
            logger.error("删除打卡项目失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } finally {
            if (endResult) {
                try {
                    String filePath = fileBizService.getUploadCIPath(memberId, "signProject");
                    String detailPath = CosBizService.getDeleteQrCodePath(filePath, projectId);
                    cosBizService.deleteFile(detailPath);
                } catch (Exception e) {
                    logger.error("删除打卡二维码失败", e);
                }
            }
        }
        return endResult;
    }
}
